package com.gc.ykqx.ui;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Environment;
import android.support.annotation.NonNull;
import android.util.Log;
import android.widget.TextView;

import com.gc.ykqx.R;
import com.gc.ykqx.service.entity.AppInfo;
import com.gc.ykqx.service.presenter.UpdatePresenter;
import com.gc.ykqx.service.util.PermissionUtils;
import com.gc.ykqx.service.view.UpdateView;
import com.gc.ykqx.ui.custom.BaseActivity;

import java.io.File;

import butterknife.BindView;
import butterknife.ButterKnife;
import util.UpdateAppUtils;

import static com.gc.ykqx.service.util.App.getContext;

public class StartActivity extends BaseActivity {

    private static final String TAG = "StartActivity";
    @BindView(R.id.tv_hint)
    TextView tvHint;
    private String dir = Environment.getExternalStorageDirectory().getAbsolutePath() + "/ykqx/pic";
    private UpdatePresenter updatePresenter;
    private Context mContext;
    private int remoteVersionCode;
    private String remoteVersionName;
    private String apkUrl;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_start);
        ButterKnife.bind(this);
        init();
    }

    /*
    检查权限
    删除图片
     */
    private void init() {
        tvHint.setText("初始化···");
        mContext = this;
        updatePresenter = new UpdatePresenter(mContext);
        updatePresenter.attachView(updateView);
        updatePresenter.onCreate();
        checkPermission();
        deleteDir(new File(dir));// TODO: 2017/10/6  delete if file.size()>10M
    }

    private UpdateView updateView = new UpdateView() {
        @Override
        public void onSuccess(AppInfo appInfo) {
            try {
                if (appInfo != null) {
                    Log.e(TAG, "版本信息->: " + appInfo.toString());
                    remoteVersionCode = Integer.valueOf(appInfo.getVersion());
                    remoteVersionName = "1."+remoteVersionCode;
                    apkUrl = appInfo.getUrl();
                    if (remoteVersionCode > getLocalVersion()) {
                        if (tvHint != null) {
                            tvHint.setText("更新中···");
                        }
                        update();
                    } else {
                        goMain();//去首页
                    }
                }
            }catch (Exception e){
                goMain();//去首页
            }
        }

        @Override
        public void onError(String result) {
            if (tvHint != null) {
                tvHint.setText("维护中");
            }
        }
    };

    public int getLocalVersion() {
        try {
            PackageInfo pi = mContext.getPackageManager().getPackageInfo(mContext.getPackageName(), 0);
            return pi.versionCode;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
            return 0;
        }
    }

    /*
    更新
     */
    private void update() {
        UpdateAppUtils.from(StartActivity.this)
                .serverVersionCode(remoteVersionCode)  //服务器versionCode
                .serverVersionName(remoteVersionName) //服务器versionName
                .apkPath("http://" + apkUrl) //最新apk下载地址i
                .update();
    }

    private void goMain() {
        Intent intent = new Intent(StartActivity.this, MainActivity.class);
        startActivity(intent);
        finish();

    }

    /*
    检查权限
     */
    private void checkPermission() {
        PermissionUtils.requestPermissionsResult(this, 1, new String[]{Manifest.permission.ACCESS_COARSE_LOCATION,
                        Manifest.permission.ACCESS_FINE_LOCATION,
                        Manifest.permission.WRITE_EXTERNAL_STORAGE,
                        Manifest.permission.READ_EXTERNAL_STORAGE},
                new PermissionUtils.OnPermissionListener() {
                    @Override
                    public void onPermissionGranted() {
                        updatePresenter.getAppInfo();
                    }

                    @Override
                    public void onPermissionDenied() {
                        PermissionUtils.showTipsDialog(getContext());
                    }
                });
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        PermissionUtils.onRequestPermissionsResult(requestCode, permissions, grantResults);
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }

    /*
     删除图片
     如果目录存在并且大于>50m
     */
    private static boolean deleteDir(File dir) {
        if (dir.isDirectory() && dir.length() >= 52428800) {
            String[] children = dir.list();//递归删除目录中的子目录下
            for (int i = 0; i < children.length; i++) {
                boolean success = deleteDir(new File(dir, children[i]));
                if (!success) {
                    return false;
                }
            }
        }
        // 目录此时为空，可以删除
        return dir.delete();
    }
}
